package tech.summerly.weather.component.fragments

import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.fragment_daily_trend.view.*
import tech.summerly.weather.R
import tech.summerly.weather.component.adapter.DailyTrendAdapter
import tech.summerly.weather.component.adapter.decoration.TemperatureItemDecoration
import tech.summerly.weather.data.bean.DailyForecast
import tech.summerly.weather.util.closeSelf
import tech.summerly.weather.util.string

class DailyTrendFragment : Fragment() {

    companion object {

        private const val DECOR_MAX = 0
        private const val DECOR_MIN = 1

        const val TAG: String = "DailyTrendFragment"
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_daily_trend, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) = with(view) {
        buttonClose.setOnClickListener {
            closeSelf()
        }
        recyclerDaily.adapter = DailyTrendAdapter()
        recyclerDaily.addItemDecoration(TemperatureItemDecoration(), DECOR_MAX)
        recyclerDaily.addItemDecoration(TemperatureItemDecoration(TemperatureItemDecoration.GRAVITY_BOTTOM), DECOR_MIN)
    }

    fun setDailyForecast(forecast: DailyForecast) = with(view) {
        this ?: return@with
        textTitle.text = string(R.string.template_daily_item_nav, forecast.aqi.size)
        (recyclerDaily.adapter as? DailyTrendAdapter)?.setData(forecast)

        val maxTemperatures = forecast.temperature.map { it.max }
        val minTemperatures = forecast.temperature.map { it.min }
        val max = maxTemperatures.max() ?: 0F
        val min = minTemperatures.min() ?: 0F
        (recyclerDaily.getItemDecorationAt(DECOR_MAX) as?
                TemperatureItemDecoration)?.setData(maxTemperatures, max, min)
        (recyclerDaily.getItemDecorationAt(DECOR_MIN) as?
                TemperatureItemDecoration)?.setData(minTemperatures, max, min)
    }

}